
#include "AudioObj.h"


void AudioObj::loadFile(string filename){
    SNDFILE *sf;

    if ((sf = sf_open(filename.c_str(), SFM_READ, &sfi)) ==NULL){
        cout << "Could not open "<< filename << "." << endl;
    }
    data.resize( (sfi.frames) * (sfi.channels) );
    sf_readf_float(sf, data.data(), data.size());
    sf_close(sf);
}

void AudioObj::saveFile(string filename){
    SNDFILE *sf;
    SF_INFO wsfi;
    wsfi.format = sfi.format;
    wsfi.channels = sfi.channels;
    wsfi.samplerate = sfi.samplerate;
    if((sf = sf_open(filename.c_str(), SFM_WRITE, &wsfi)) == NULL){
        cout << "Could not open " << filename << endl;
    }
    sf_writef_float(sf, data.data(), sfi.frames);//data.size()/sfi.channels);
    sf_close(sf);
}
void AudioObj::setData(vector<float> outdata){
    data.assign(outdata.begin(), outdata.end());
    sfi.frames = data.size()/sfi.channels;
    return;
}
vector<float> AudioObj::getData(){
    return data;
}

//Get data in range [m, m+n) FRAME
int AudioObj::getData(vector<float> *tmp, int m, int n){
    //process of the end of the file
    if ((m+n)*sfi.channels >= data.size())
        n = (data.size() - m * sfi.channels) / sfi.channels;
    tmp->assign(data.begin() + m * sfi.channels, data.begin() + (m + n) * sfi.channels);
    return tmp->size()/sfi.channels;
}
int AudioObj::getFrames(){
    return sfi.frames;
}
int AudioObj::getSamplerate(){
    return sfi.samplerate;
}
int AudioObj::getChannels(){
    return sfi.channels;
}

            

